package com.fs.system.web.controller.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.fs.common.config.RuoYiConfig;
import com.fs.common.constant.CacheConstants;
import com.fs.common.constant.Constants;
import com.fs.common.core.vo.AjaxResult;
import com.fs.common.util.RedisCache;
import com.fs.system.service.ISysConfigService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;




    /**
     * 生成验证码  -> 返回数据 (图片)
     */
//    @GetMapping("/captchaImage")
//    public AjaxResult getCode(HttpServletResponse response) throws IOException
//    {
//        // 第一步
//        if (configService.selectCaptchaEnabled()) {
//            // 生成运算验证码文本  -> 前一段交给前台  一段(答案)交给redis
////            String captchaText = captchaProducer.createText();
//            String MathTextExpress = captchaProducerMath.createText();
//            String a = MathTextExpress.substring(MathTextExpress.lastIndexOf("@")+1);
//            MathTextExpress = MathTextExpress.substring(0, MathTextExpress.lastIndexOf("@"));
//
//            String uuid = UUID.randomUUID().toString();
//            String captchaKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
//            redisCache.setCacheObject(captchaKey, MathTextExpress, configService.selectCaptchaExpireTime(), TimeUnit.MINUTES);
//
//            BufferedImage image = captchaProducer.createImage(MathTextExpress);
//
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            ImageIO.write(image, "gif", outputStream);
//            String base64Image = Base64.encode(outputStream.toByteArray());
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("img", base64Image);
//            map.put("uuid", uuid);
//            System.out.println("============================="+map);
//            return AjaxResult.success("操作成功", map);
//        } else {
//            return AjaxResult.error("验证码没用！！");
//        }
//    }





    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse httpServletResponse)throws IOException{
        //查看数据库配置中是否开启验证
        boolean isOpen = configService.selectCaptchaEnabled();
        //从RuoYIConfig中查看验证码的类型
        String captchaType = RuoYiConfig.getCaptchaType();
        AjaxResult ajaxResult = AjaxResult.success();
        String caparigthExpress = null;//前缀表达式 -> 给到前端当中去
        String resultStr = null;//后缀结果 -> 存到redis
        BufferedImage image = null;//生成验证码的图片

        //定义存放好的key(前缀+uuid)
        String uuid = UUID.randomUUID().toString();//true
        String key = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        if(isOpen){
            //根据验证码的类型调用验证码的工具类生成验证码 -> 类似于这种结果 1+1=？@2
            if("math".equals(captchaType)){
                String capstr = captchaProducerMath.createText();
                caparigthExpress = capstr.substring(0, capstr.lastIndexOf("@"));
                resultStr = capstr.substring(capstr.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(caparigthExpress);
            }else if("char".equals(captchaType)){
                String captchaProducerText = captchaProducer.createText();
                image = captchaProducer.createImage(captchaProducerText);
            }
            redisCache.setCacheObject(key,resultStr,Constants.CAPTCHA_EXPIRATION,TimeUnit.MINUTES);
            FastByteArrayOutputStream fastByteArrayOutputStream = new FastByteArrayOutputStream();
            ImageIO.write(image,"jpg",fastByteArrayOutputStream);
            String base64Image = Base64.encode(fastByteArrayOutputStream.toByteArray());
            ajaxResult.put("isOpen",isOpen);
            ajaxResult.put("img","data:image/jpeg;base64,"+Base64.encode(fastByteArrayOutputStream.toByteArray()));
            ajaxResult.put("uuid",uuid);
            return ajaxResult;
        }
        if(!isOpen){return AjaxResult.error("验证码服务未开启");}
        return null;
    }


}
